package pages.loginPage;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import pages.menuPage.MenuPage;

public class LoginPage extends WebPage
{
	private static final long serialVersionUID = 1L;
	
	private IModel<LoginPageModelObject> pageModel;
	private Form<LoginPageModelObject> form;
	private FeedbackPanel feedbackPanel;
	
	public LoginPage()
	{
		initContent();
	}

	private void initContent() 
	{
		pageModel = new CompoundPropertyModel<LoginPageModelObject>(new LoginPageModelObject());
		form = new Form<LoginPageModelObject>("form", pageModel);
		form.setOutputMarkupId(true);
		add(form);
		
		RequiredTextField<String> userTextField = new RequiredTextField<String>("userId", new PropertyModel<String>(pageModel, "userId"));
		form.add(userTextField);
		
		PasswordTextField passwordTextField = new PasswordTextField("password", new PropertyModel<String>(pageModel, "password"));
		form.add(passwordTextField);
		
		feedbackPanel = new FeedbackPanel("feedbackPanel");
		feedbackPanel.setOutputMarkupId(true);
		form.add(feedbackPanel);
		
		addButton();
	}

	private void addButton() 
	{
		AjaxFallbackButton loginButton = new AjaxFallbackButton("loginButton", form) 
		{
			private static final long serialVersionUID = 1L;
			
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form)
            {
                super.onSubmit(target, form);
                AuthenticatedWebSession authSession = AuthenticatedWebSession.get();
                if (authSession.signIn(pageModel.getObject().getUserId(), pageModel.getObject().getPassword()))
                {
                	System.out.println("login button submit");
                	setResponsePage(MenuPage.class);
                }
                else
                {
                	error("Login failed!");
//                	target.add(feedbackPanel);
                }
            }
		};
		form.add(loginButton);
		
	}

}
